# server_msapp.py
from flask import Flask, request, send_file
import os
import socket
from testPspSleepV3Demo import run_upload
from sleepPng import generate_png
from zeroconf import Zeroconf, ServiceInfo

app = Flask(__name__)

# 创建目录
os.makedirs("./uploaded", exist_ok=True)
os.makedirs("./received_from_server", exist_ok=True)

# 获取局域网 IP
def get_local_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
    except:
        ip = "127.0.0.1"
    finally:
        s.close()
    return ip

LOCAL_IP = get_local_ip()
PORT = 8080
SERVICE_NAME = "msapp._http._tcp.local."

# 注册 Zeroconf 服务
zeroconf = Zeroconf()
info = ServiceInfo(
    "_http._tcp.local.",
    SERVICE_NAME,
    addresses=[socket.inet_aton(LOCAL_IP)],
    port=PORT,
    properties={},
    server="msapp.philips."
)

try:
    zeroconf.register_service(info, allow_name_change=True)
    print(f"[Zeroconf] 服务已注册: {SERVICE_NAME}, IP: {LOCAL_IP}:{PORT}")
except Exception as e:
    print(f"[Zeroconf] 注册失败: {e}")

@app.route("/upload", methods=["POST"])
def upload():
    file = request.files.get("file")
    if not file:
        return {"error": "no file"}, 400

    # 清理 uploaded 目录
    for f in os.listdir("./uploaded"):
        os.remove(os.path.join("./uploaded", f))

    file_path = os.path.join("./uploaded", file.filename)
    file.save(file_path)
    print(f"[server] 文件已保存到 uploaded: {file_path}")

    # 上传 txt 到服务器，返回回传 txt
    returned_txt = run_upload(file_path)
    if not returned_txt:
        return {"error": "server upload failed"}, 500

    # 生成 PNG 并返回
    png_path = generate_png(returned_txt)
    return send_file(png_path, as_attachment=True)

if __name__ == "__main__":
    print(f"[Flask] 运行在 http://{LOCAL_IP}:{PORT}")
    app.run(host="0.0.0.0", port=PORT, debug=True)
